<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { computed, reactive, ref, watch } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { getVxePopupContainer } from '@vben/utils';

import { PlusOutlined } from '@ant-design/icons-vue';
import { Popconfirm, Segmented, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { removeTopic, topicList } from '#/api/iot/product/topic';
import { renderDict } from '#/utils/render';

import { TopicType } from '../data';
import topicFormModel from './topic-form-model.vue';

interface Props {
  productId: string;
}

const props = defineProps<Props>();

watch(
  () => props.productId,
  async (newProductId) => {
    if (newProductId) {
      await tableApi.query();
    }
  },
);
const [TopicFormModel, drawerApi] = useVbenDrawer({
  connectedComponent: topicFormModel,
});

const topicClassify = ref<TopicType>(TopicType.System);
const isCustomTopic = computed(() => topicClassify.value === TopicType.Custom);

// const alertMessage = computed(() =>
//   isCustomTopic.value
//     ? 'Topic用以将设备数据分类上报，进而分别进行处理。除了系统预置的Topic，您也可以自定义Topic，然后在设备侧开发时选择数据上报的Topic。'
//     : '以下是系统Topic，设备侧通过系统预设的topic接收数据时，无需提前订阅。',
// );

const gridOptions = reactive<VxeGridProps>({
  columns: [
    {
      title: 'Topic',
      field: 'topic',
    },
    {
      title: '操作权限',
      field: 'topicDirection',
      slots: {
        default: ({ row }) => {
          return renderDict(`${row.topicDirection}`, DictEnum.IOT_TOPIC_TYPE);
        },
      },
    },

    {
      title: '描述',
      field: 'topicDesc',
    },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '操作',
      resizable: false,
    },
  ],
  minHeight: 300,
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const data = await topicList({
          productId: props.productId,
          topicSourceType: 2,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return {
          rows: data.rows,
          total: data.total,
        };
      },
    },
  },

  toolbarConfig: {
    custom: false,
  },

  rowConfig: {
    keyField: 'id',
  },
  id: 'iot-topic-index',
});
const gridOptions2 = reactive<VxeGridProps>({
  columns: [
    {
      title: 'Topic',
      field: 'topic',
    },
    {
      title: '操作权限',
      field: 'topicDirection',
      slots: {
        default: ({ row }) => {
          return renderDict(`${row.topicDirection}`, DictEnum.IOT_TOPIC_TYPE);
        },
      },
    },

    {
      title: '描述',
      field: 'topicDesc',
    },
  ],
  minHeight: 300,
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const data = await topicList({
          productId: props.productId,
          topicSourceType: 1,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return {
          rows: data.rows,
          total: data.total,
        };
      },
    },
  },

  toolbarConfig: {
    custom: false,
  },

  rowConfig: {
    keyField: 'id',
  },
  id: 'iot-topic-index',
});

const [BasicTable2, tableApi2] = useVbenVxeGrid({
  gridOptions: gridOptions2,
});
const [BasicTable, tableApi] = useVbenVxeGrid({
  gridOptions,
});

function onChangeTopicType() {
  console.log(isCustomTopic.value);
  if (isCustomTopic.value) {
    tableApi2.query();
  } else {
    tableApi.query();
  }
}
function handleAdd() {
  drawerApi.setData({
    productId: props.productId,
  });
  drawerApi.open();
}
async function handleEdit(record: Recordable<any>) {
  drawerApi.setData({ id: record.id });
  drawerApi.open();
}
async function handleDeleteTopic(row: Recordable<any>) {
  await removeTopic(row.id);
  await tableApi2.query();
}
</script>

<template>
  <div class="flex h-full flex-col gap-[16px]">
    <div class="flex items-center justify-between" mb="12px">
      <div class="flex items-center gap-x-3">
        <Segmented
          v-model:value="topicClassify"
          :options="[
            { label: '系统 Topic', value: TopicType.System },
            { label: '自定义 Topic', value: TopicType.Custom },
          ]"
          @change="onChangeTopicType"
        />
      </div>
    </div>

    <BasicTable table-title="Topic 列表" v-if="isCustomTopic">
      <template #toolbar-tools>
        <Space>
          <a-button
            v-if="isCustomTopic"
            v-access:code="['iot:topic:add']"
            type="primary"
            @click="handleAdd"
          >
            <PlusOutlined />
            新增
          </a-button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['iot:topic:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDeleteTopic(row)"
          >
            <ghost-button
              danger
              v-access:code="['iot:topic:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <BasicTable2 table-title="Topic 列表" v-else />
    <TopicFormModel @reload="tableApi.query()" />
  </div>
</template>
